//
//  BattleViewController.m
//  PacIsBack
//
//  Created by Jérémy Brault on 21/01/10.
//  Copyright 2010 None. All rights reserved.
//

#import "BattleViewController.h"
#import "BattleTeamProtocol.h"
#import "RPGImageView.h"
#import "CharacterProtocol.h"
#import "CharacterViewController.h"
#import "Constants.h"
#import "InfoAreaViewController.h"
#import "ActionSelectionViewController.h"

@implementation BattleViewController

@synthesize backGround,player, battle, music, currentAttackOrigin, currentAttackTarget, defeatOrVictoryView, backgroundView, infoArea, actionSelection, fightEnded;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

//TODO private method, music selection
-(void) playBattleMusic{
	[self setPlayer:[MusicController instance]];
	[[self player] playMusic:[self music]];
}

-(void) updateInfoArea{
	if ([self actionSelection] == nil) {
		if ([self infoArea] == nil) {
			InfoAreaViewController* infos = [[InfoAreaViewController alloc] initEmpty];
			[self setInfoArea:infos];
			[infos release];
		}
		[[self view] addSubview:[[self infoArea] view]];
	}
	else {
		[[[self infoArea] view] removeFromSuperview];
		[[self view] addSubview:[[self actionSelection] view]];
	}
}


-(void) updateBackgroundAndMusic{
	NSString *imageName;
	imageName = [NSString stringWithFormat:@"%@%@",[self backGround],@".png"];
	UIImage* tmpImage = [UIImage imageNamed:imageName];
	UIImageView* initBackgroundView = [[RPGImageView alloc] init];
	[initBackgroundView setImage:tmpImage];
	[initBackgroundView sizeToFit];
	[self setBackgroundView:initBackgroundView];
	[initBackgroundView release];
	[[self view] addSubview:initBackgroundView];
	[self playBattleMusic];
	[self updateInfoArea];
}

/*-(id) initWithBackGround:(NSString*) initBG{
	if (self = [super init]) {
        [self setBackGround:initBG];
		[self setMusic:@"battle"];
		NSString *imageName;
		imageName = [NSString stringWithFormat:@"%@%@",[self backGround],@".png"];
		UIImage* tmpImage = [UIImage imageNamed:imageName];
		UIImageView* initialView = [[RPGImageView alloc] init];
		[initialView setImage:tmpImage];
		[self setView:initialView];
		[initialView release];
		[self playBattleMusic];
    }
    return self;
}*/


-(id) initForModel:(id<BattleProtocol>) model{
	if (self = [super init]) {
		[self setBattle:model];
		[self setFightEnded:NO];
		[self setBackGround:[[self battle] background]];
		[self setMusic:[[self battle] musicType]];
		UIView* emptyView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, iphoneWidth, iphoneHeight)];
		[self setView:emptyView];
		[emptyView release];
		[self updateBackgroundAndMusic];
		UIView* playerTeamView = [[[[self battle] playerTeam] controller] view];
		[[self view] addSubview:playerTeamView];
		UIView* ennemyTeamView = [[[[self battle] ennemyTeam] controller] view];
		[[self view] addSubview:ennemyTeamView];
	}
    return self;
}

-(void) executeAttackFrom:(id<CharacterProtocol>) origin toTarget:(id<CharacterProtocol>) target{
	[self setCurrentAttackOrigin:origin];
	[self setCurrentAttackTarget:target];
	CGPoint targetLocation = [[[target battleController] view] center];
	targetLocation = [[[origin battleController] view] convertPoint:targetLocation fromView:[[target battleController] view]];
	if (targetLocation.x>[[[origin battleController] view] center].x) {
		targetLocation.x = targetLocation.x-attackDistanceGap;
	}
	else {
		targetLocation.x = targetLocation.x+attackDistanceGap;
	}
	NSValue* targetValue = [NSValue valueWithCGPoint:targetLocation];
	[[origin battleController] performSelectorOnMainThread:@selector(executeAttackWithNSValue:) withObject:targetValue waitUntilDone:YES];
}

-(void) attackInflictDamage{
	NSInteger damages = [[self battle] inflictDamageFrom:[self currentAttackOrigin] toTarget:[self currentAttackTarget]];
	[[[self currentAttackTarget] battleController] showDamages:damages];
	[[[self currentAttackTarget] battleController] changeHealth:[[self currentAttackTarget] currentHP]];
}
-(void) defeat{
	[self setFightEnded:YES];
	UIImage* defeatImage = [UIImage imageNamed:@"Defeat.png"];
	UIImageView* defeatView = [[RPGImageView alloc] init];
	[defeatView setImage:defeatImage];
	[self setDefeatOrVictoryView:defeatView];
	[defeatView release];
	[self defeatOrVictoryAnimate];
}

-(void) victory{
	[self setFightEnded:YES];
	UIImage* victoryImage = [UIImage imageNamed:@"Victory.png"];
	UIImageView* victoryView = [[RPGImageView alloc] init];
	[victoryView setImage:victoryImage];
	[self setDefeatOrVictoryView:victoryView];
	[victoryView release];
	[self defeatOrVictoryAnimate];
}

-(void) defeatOrVictoryAnimate{
	[[self defeatOrVictoryView] setCenter:CGPointMake(resultImageInitialPositionX, resultImageInitialPositionY)];
	[[self defeatOrVictoryView] sizeToFit];
	[[self view] addSubview:[self defeatOrVictoryView]];
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(defeatOrVictoryEndAnimation)];
	[UIView setAnimationDuration:resultImageTravelDuration];
	[[self defeatOrVictoryView] setCenter:[[self view] center]];
	[UIView commitAnimations];	
}

-(void) defeatOrVictoryEndAnimation{
	[[self view] bringSubviewToFront:[[self infoArea] view]];
	[[self battle] processEndOfFight];
}

-(void) showInfo:(NSString*) info{
	[[self infoArea] addLine:info];
}

-(void) showAbilityAreaOfCharacter:(id<CharacterProtocol>) character{
	ActionSelectionViewController* newActSelect = [[ActionSelectionViewController alloc] initForCharacter:character];
	[self setActionSelection:newActSelect];
	[newActSelect release];
	[self updateInfoArea];
}

-(void) removeAbilityArea{
	if ([self actionSelection] != nil) {
		[[[self actionSelection] view] removeFromSuperview];
		[self setActionSelection:nil];
		[self updateInfoArea];
	}
}

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
	if ([self fightEnded]) {
		[[self battle] goToNextEventAfterFightEnd];
	}
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[self setBackGround:nil];
	[self setBattle:nil];
	[self setMusic:nil];
	[self setCurrentAttackOrigin:nil];
	[self setCurrentAttackTarget:nil];
	[self setDefeatOrVictoryView:nil];
	[self setBackgroundView:nil];
	[self setInfoArea:nil];
	[self setActionSelection:nil];
	[self setFightEnded:YES];
   [super dealloc];
}

@end
